#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "../include/sreialPort.h"
#include "sqliteinterface.h"

#define FILEPATH_MAX (80)

int maxtmp = 40;//定义好的最大温度，防止风扇和蜂鸣器最初的干扰
int maxhum = 40;//默认最大湿度
int minlight = 30;	//30一下开灯
int flag =0;//定义的标志位
int light_flag = 0;
int ID;   //发送socket fd
extern unsigned int rgb_buf_size;//应用串口的文件
extern unsigned int jpg_buf_size;
extern unsigned char *rgb_buf ;
extern unsigned char *jpg_buf ;
extern unsigned long outsize ;//每一个jpg的大小
extern int card_flag;

int InitDb()//创建数据库/打开数据库
{
    /*db name start*/
    char *pPath = NULL;//数据库已经写好
    char dbName[] = "/mysqlite.db";
    pPath = (char *) malloc (FILEPATH_MAX + 10);
    if (NULL == pPath)
    {
        return DB_ERR;
    }
    memset(pPath, 0, FILEPATH_MAX + 10);
    getcwd(pPath, FILEPATH_MAX);
   // printf("%s %d\n",pPath,strlen(pPath));
    memcpy(pPath + strlen(pPath), dbName, strlen(dbName));
    //printf("%s %d\n",pPath,strlen(pPath));
    /*db name end*/
    //init db
    if (DB_ERROR_OK != InitConnection())//初始化数据库
    {
        printf("invoke InitConnection function error!\n");
        return DB_ERR;
    }
    //open or create db
    if (DB_ERROR_OK != OpenConnection(pPath))//如果没有数据库，创建数据库
    {
        printf("invoke OpenConnection function error!\n");
        return DB_ERR;
    }

	CreateTable();
	
    return DB_OK;
}

int CreateTable()//创建管理员帐号密码表、用户帐号密码表
{
	char Administrator[] = "create table admin (id integer primary key autoincrement,"//创建密码
							" admin_name text not null,"//管理员名字 不能为空
							" admin_password text not null )";//密码 文本型不能为空
							
	if (DB_ERROR_OK != ExecSQL(Administrator))//执行ExecSQL语句
    	{
		//perror("create passenger table error\n");
        	return DB_ERR;
    	}
 	char User[] = "create table user (id integer primary key autoincrement,"//创建用户表
                                                    "user_name text not null,"
                                                    "user_password text not null)";
    	if (DB_ERROR_OK != ExecSQL(User))
    	{
		//perror("create User table error\n");
        	return DB_ERR;
    	}
		
	char Card[] = "create table card (id integer primary key autoincrement,"//创建card表
                                                    "card_id text not null)";
    	if (DB_ERROR_OK != ExecSQL(Card))
    	{
			perror("create card table error\n");
        	return DB_ERR;
    	}

	char Environment[]="create table environment (id integer primary key autoincrement,"
                                                    "temperature text not null,"
						    "humidity text not null,"
						    "illumination text not null,"//关照强度不能为空
                                                    "nowtime text not null)";//获得当前时间
	if (DB_ERROR_OK != ExecSQL(Environment))
    	{
		//perror("create Environment table error\n");
        	return DB_ERR;
    	}

	printf("create table ok!!!\n");

	char AdminInsert[]="insert into admin (id, admin_name, admin_password) values (1,'admin','admin')";//创建一个管理员账号
	if (DB_ERROR_OK != ExecSQL(AdminInsert))
    	{
        	printf("insert table sql error\n");
		return DB_ERR;
    	}

	char UserInsert[]="insert into user (id, user_name, user_password) values (1,'user','user')";
	if (DB_ERROR_OK != ExecSQL(UserInsert))
    	{
        	printf("insert table sql error\n");
		return DB_ERR;
    	}
	char str[200] = "insert into environment (id,temperature, humidity ,illumination,nowtime) values (1,'30','26','55','2018.4.10')";
	if (DB_ERROR_OK != ExecSQL(str))//插入的环境变量
    	{
        	printf("insert table sql error\n");
		return DB_ERR;
    	}
	return DB_OK;
}

int FindCard(char * id)//查找用户注册是否重复
{
	char buf[100]; 
	/*
	char findId[100]="select * from card where card_id = id;
	strcat(findName,buf);
	strcat(findName,"'");
	*/
	char** ppTable = NULL;
	sprintf(buf,"select * from card where card_id = '%s'",id);
    int iRow = 0;
    int iColumn = 0;
	if (DB_ERROR_OK != GetTable(buf, &ppTable, &iRow, &iColumn))
    {
		return DB_ERR;
    }
	if (NULL != ppTable)
    {
		if(iRow >= 1)
		{
			return DB_OK;		
		}
		return DB_ERR;
	}
    ReleaseTableResult(ppTable);
}

int RID(int socketID,char *buffer[])//ID 注册
{
	char buf[50] = "rid,double_err";//注册失败，发送buf
	//printf("user_name = %s\n",buffer[1]);
	if(DB_OK ==FindCard(buffer[1]))//如果注册重复，提示注册名失败
	{
		printf("id zhuce error!\n");
		send(socketID, buf, strlen(buf), 0);//发送给客户端注册失败
		return DB_ERR;
    };
	char idInsert[200]={0};
	sprintf(idInsert,"insert into card (card_id) values ('%s')",buffer[1]);
	if (DB_ERROR_OK != ExecSQL(idInsert))
    {
        printf("id zhuce error!!\n");
		return DB_ERR;
    }
	char buff[30] = "rid,ok";
	send(socketID, buff, strlen(buff), 0);
	return DB_OK;
}



int DID(int socketID,char *buffer[])
{
	char idDel[200]={0};
	sprintf(idDel,"delete from card where card_id = ('%s')",buffer[1]);
	if (DB_ERROR_OK != ExecSQL(idDel))
    {
		char buf[30] = "rid,del_err";
		send(socketID, buf, strlen(buf), 0);
		return DB_ERR;
    }
	char buff[30] = "rid,del_ok";
	send(socketID, buff, strlen(buff), 0);
	return DB_OK;	
}

int Zhuce(int socketID,char *buffer[])//用户帐号注册
{
	char buf[50] = "ZhuceError";//注册失败，发送buf
	//printf("user_name = %s\n",buffer[1]);
	if(DB_OK ==FindTable(buffer[1]))//如果注册重复，提示注册名失败
	{
		printf("username zhuce error!\n");
		send(socketID, buf, strlen(buf), 0);//发送给客户端注册失败
		return DB_ERR;
    };
	char UserInsert[200]="insert into user (user_name, user_password) values ('";
	strcat(UserInsert,buffer[1]);//注册的用户名
	strcat(UserInsert,"','");
	strcat(UserInsert,buffer[2]);//注册的用户密码
	strcat(UserInsert,"')");
	if (DB_ERROR_OK != ExecSQL(UserInsert))
    	{
        	printf("username zhuce error!!\n");
		return DB_ERR;
    	}
	//printf("zhuce ok!\n");
	char buff[30] = "ZhuceSucced";
	send(socketID, buff, strlen(buff), 0);
	return DB_OK;
}

int Login(int socketID,char *buffer[])//用户登录
{

	char adminSuccedbuf[50] = "adminLoginSucced";//管理员登录成功
	char userSuccedbuf[50] = "userLoginSucced";//普通用户登录成功
	char Errorbuf[50] = "LoginError";//登录错误
	if(0 ==strcmp("admin",buffer[1]))
	{
		char Admin[100] = "select * from admin where admin_password = '";
		strcat(Admin,buffer[2]);
		strcat(Admin,"'");
		char** ppTable = NULL;
    		int iRow = 0;
    		int iColumn = 0;
		if (DB_ERROR_OK != GetTable(Admin, &ppTable, &iRow, &iColumn))
    		{
			return DB_ERR;
    		}
		if (NULL != ppTable)
    		{
			if(0 == strcmp(buffer[1],ppTable[4]) && 0 == strcmp(buffer[2],ppTable[5]))
			{
				printf("admin login ok!\n");
				send(socketID, adminSuccedbuf, strlen(adminSuccedbuf), 0);
				return DB_OK;		
			}
			printf("admin login error!\n");
			send(socketID, Errorbuf, strlen(Errorbuf), 0);
			return DB_ERR;
		}
	}
	else
	{
		char User[100] = "select * from user where user_name = '";//查找用户名必须是buffer[1]里面的用户名，密码必须是用户密码
		strcat(User,buffer[1]);
		strcat(User,"'");
		strcat(User,"and user_password = '");
		strcat(User,buffer[2]);
		strcat(User,"'");
		char** ppTable = NULL;//查找的内容放在二级指针/select * from user where user_name
    		int iRow = 0;//查找的行
    		int iColumn = 0;//查找的列
		if (DB_ERROR_OK != GetTable(User, &ppTable, &iRow, &iColumn))
    		{
			return DB_ERR;
    		}
		if (NULL != ppTable)
    		{
			if(0 == strcmp(buffer[1],ppTable[4]) && 0 == strcmp(buffer[2],ppTable[5]))
			{
				printf("user login ok!\n");
				send(socketID, userSuccedbuf, strlen(userSuccedbuf), 0);
				return DB_OK;		
			}
			printf("user login error!\n");
			send(socketID, Errorbuf, strlen(Errorbuf), 0);
			return DB_ERR;
		}
	}
}


int FindTable(const char *buf)//查找用户注册是否重复
{
	if(NULL == buf)
	{
		printf("find error\n");
	}
	char findName[100]="select * from user where user_name = '";
	strcat(findName,buf);
	strcat(findName,"'");
	char** ppTable = NULL;
    	int iRow = 0;
    	int iColumn = 0;
	if (DB_ERROR_OK != GetTable(findName, &ppTable, &iRow, &iColumn))
    	{
		return DB_ERR;
    	}
	if (NULL != ppTable)
    	{
		if(0 == strcmp(buf,ppTable[4]))
		{
			return DB_OK;		
		}
		return DB_ERR;
	}
    	ReleaseTableResult(ppTable);
	return DB_OK;
}


int InsertEnvironment(int tmp,int hum,int light)//插入的环境变量
{

	//printf("tmp = %d hum = %d light = %d \n",tmp,hum,light);
	char EnvironmentInsert[200]="insert into environment (temperature, humidity ,illumination,nowtime) values ('";
	char temp[50] ;
	char humidity[50];
	char illumination[50];
	sprintf(temp,"%d",tmp);
	sprintf(humidity,"%d",hum);
	sprintf(illumination,"%d",light);
	//printf("tmp1 = %s hum1 = %s light1 = %s\n",temp,humidity,illumination);
	time_t timer;
    	struct tm *tblock;
    	timer = time(NULL);
    	tblock = localtime(&timer);
	char *nowtime = asctime(tblock);
	strcat(EnvironmentInsert,temp);
	strcat(EnvironmentInsert,"','");
	strcat(EnvironmentInsert,humidity);
	strcat(EnvironmentInsert,"','");
	strcat(EnvironmentInsert,illumination);
	strcat(EnvironmentInsert,"','");
	strcat(EnvironmentInsert,nowtime);
	strcat(EnvironmentInsert,"')");
	if (DB_ERROR_OK != ExecSQL(EnvironmentInsert))
    	{
        	printf("insert table sql error\n");
		return DB_ERR;
    	}
	return DB_OK;
}


int Begin(int socketID,char *buffer[])//发送数据到客户端
{
	char select[100] = "select * from environment";
	char** ppTable = NULL;
    	char* pErrMsg = NULL;
    	int iRow = 0;
    	int iColumn = 0;
	char buf[200] = "begin,";
    	if (DB_ERROR_OK != GetTable(select, &ppTable, &iRow, &iColumn))
    	{
        	printf("select sql error\n");
		return DB_ERR;
    	}
	int a = iRow*5+1;
	int i;
	for(i = 0;i < 4;i++)
	{
		strcat(buf,ppTable[a]);//
		strcat(buf,",");
		a++;
	}
	printf("\n");
	send(socketID, buf, strlen(buf), 0);//将buf传送到客户端
    	ReleaseTableResult(ppTable);
	
	return DB_OK;	
}

void *threadFunc3(void *socket)   //视频线程处理
{
	camera_run();
}

int cameraOpen(int socketID,char *buffer[])  //创建视频处理线程
{
	
	ID = socketID;
	pthread_t threadID3;
	int ret = pthread_create(&threadID3, NULL, threadFunc3,NULL);

    	if(ret != 0)
    	{
        	printf("create pthread error!\n");
        	return -1;
    	}
	
}


//客户端发送指令执行函数
int OpenFan(int socketID,char *buffer[])
{
	cmd_anal(MOfd,3,5);
	return DB_OK;
}

int CloseFan(int socketID,char *buffer[])
{
	cmd_anal(MOfd,4,5);
	return DB_OK;
}

int OpenBuzzer(int socketID,char *buffer[])
{
	cmd_anal(MOfd,5,5);
	return DB_OK;
}
int CloseBuzzer(int socketID,char *buffer[])
{
	cmd_anal(MOfd,6,5);
	return DB_OK;
}

int OpenLed(int socketID,char *buffer[])
{
	light_flag = 1;
	cmd_anal(MOfd,1,5);
	return DB_OK;
}
int CloseLed(int socketID,char *buffer[])
{
	light_flag = 0;
	cmd_anal(MOfd,2,5);
	return DB_OK;
}

//客户端设置阈值
int Tmp(int socketID,char *buffer[])
{
	maxtmp = atoi(buffer[1]);
	printf("maxtmp = %d\n",maxtmp);
	return DB_OK;
}
int Hum(int socketID,char *buffer[])
{
	maxhum = atoi(buffer[1]);
	return DB_OK;
}
int Light(int socketID,char *buffer[])
{
	minlight = atoi(buffer[1]);
	return DB_OK;
}

//cmp-----发送指令到M0，控制温湿度、光强
void cmp(int tmp,int hum,int light)
{
	if(tmp >= maxtmp)
	{
		printf("maxtmp = %d\n",maxtmp);
		printf("tmp<<<<<<<<<<3\n");
		cmd_anal(MOfd,3,5);
	}
	else if(tmp < (maxtmp - 5))
	{
		printf("tmp <<<<< 4\n");
		cmd_anal(MOfd,4,5);

	}
	if(hum > maxhum)
	{
		printf("hum <<<<< 5\n");
		cmd_anal(MOfd,5,5);
	}
	else if(hum < (maxhum - 5))
	{
		printf("hum <<<<< 6\n");
			cmd_anal(MOfd,6,5);
	}
	if((light < minlight) && (0 == light_flag))
	{	
		printf("light<<<<< 1\n");
		cmd_anal(MOfd,1,5);	
	}
	else if((light > (minlight + 30)) && (0 == light_flag))
	{
		printf("light <<<<< 2\n");
		cmd_anal(MOfd,2,5);
	}
}



